﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using AutodeskInventorInterfaces.Model;
using Inventor;

namespace AutodeskInventorInterfaces.Extend
{
  public static class Extensions
  {
    public static ClientParameter ToClientParameter(this Parameter parameter)
    {
      var units = string.Empty;
      try
      {
        units = parameter.get_Units();
      }
      catch { }
      if (string.IsNullOrEmpty(units))
      {
        try
        {
          units = ((dynamic)parameter).Units;
        }
        catch { }
      }
      return new ClientParameter { Name = parameter.Name, Value = parameter.Value, Units = units };
    }

    public static ClientHoleFeature ToClientFeature(this HoleFeature holeFeature)
    {
      return new ClientHoleFeature(holeFeature);
    }

    public static string ToRelativePath(this string path)
    {
      return path.Replace(AppContext.BaseDirectory, "").Replace('\\', '/').ToLower();
    }

    public static string ToAbsolutePath(this string path)
    {
      if (VirtualPathUtility.IsAbsolute(path) || VirtualPathUtility.IsAppRelative(path))
      {
        return HttpContext.Current.Server.MapPath(VirtualPathUtility.ToAbsolute(path));
      }
      return System.IO.Path.Combine(AppContext.BaseDirectory, path.Replace("/", "\\"));
    }

    public static IList<TResult> Map<TSource, TResult>(this IList<TSource> list, Func<TSource, TResult> handler, bool ignoreNull = false)
    {
      var listResult = new List<TResult>();
      foreach (var ele in list)
      {
        var res = handler(ele);
        if (ignoreNull && res == null)
        {
          continue;
        }
        listResult.Add(res);
      }
      return listResult;
    }

    public static bool IsNotNullOrEmpty(this string exp)
    {
      return !String.IsNullOrEmpty(exp);
    }

    public static bool IsNullOrEmpty(this string exp)
    {
      return String.IsNullOrEmpty(exp);
    }

    /// <summary>
    /// 判断文件是否是装配文件或者工程图
    /// </summary>
    /// <param name="exp"></param>
    /// <returns></returns>
    public static bool IsAssemblyFile(this string exp)
    {
      exp = exp.ToLower();
      return exp.EndsWith(".iam") || exp.EndsWith(".idw");
    }

    /// <summary>
    /// 只获取名称，不要后缀
    /// </summary>
    /// <param name="fileInfo"></param>
    /// <returns></returns>
    public static string OnlyName(this FileInfo fileInfo)
    {
      return fileInfo.Name.Substring(0, fileInfo.Name.Length - fileInfo.Extension.Length);
    }
  }
}